<?php

$depends = array();
$loaded = array();

function include_recursively( $path ) {
	global $depends;
	$dh = opendir( $path );
	while( $item = readdir( $dh ) ) {
		if( $item[0] == '.' ) continue;
		$item = $path . '/' . $item ;
		if( substr($item, -3) == '.js' ) {
			$content = file_get_contents( $item );
			preg_match_all( '/@depends (\S+)/', $content, $match, PREG_SET_ORDER );
			$deps = array();
			foreach( $match as $v ) {
				$deps[] = __DIR__ . '/' . $v[1];
			}
			$depends[ $item ] = array(
				'deps' => $deps,
				'content' => $content );
			continue;
		}
		if( is_dir( $item ) ) {
			include_recursively( $item );
		}
	}
}

header( 'Content-Type: text/javascript' );
echo 'Widgets = {};';
include_recursively( __DIR__ );

while( $depends ) {
	foreach( $depends as $item => $depend ) {
		foreach( $depend['deps'] as $i => $dep ) {
			if( isset($loaded[$dep]) ) {
				unset($depends[$item]['deps'][$i]);
			}
		}
		if( !$depends[$item]['deps'][$i] ) {
			$loaded[$item] = true;
			echo ';' . $depend['content'];
			unset($depends[$item]);
		}
	}
}
